//
//  Myview.m
//  涂鸦
//
//  Created by mafeng on 16/7/11.
//  Copyright © 2016年 mafeng. All rights reserved.
//

#import "Myview.h"
#import "ModleOfMyview.h"
@interface Myview ()
@property (nonatomic, assign) CGMutablePathRef path;
@property (nonatomic, retain) NSMutableArray *pathArray;
@property (nonatomic, assign)BOOL isHavePath;
@end

@implementation Myview

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/
- (id)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor cyanColor];
        _lineColor = [UIColor yellowColor];
        _lineWidth = 10.0f;
    }
    return self;
}
- (void)drawRect:(CGRect)rect {
    CGContextRef context = UIGraphicsGetCurrentContext();
    [self drawView:context];
}
- (void)drawView:(CGContextRef)context {
    for (ModleOfMyview *modelOfMyview in _pathArray) {
        CGContextAddPath(context, modelOfMyview.path.CGPath);
        [modelOfMyview.color set];
        CGContextSetLineWidth(context, modelOfMyview.width);
        CGContextSetLineCap(context, kCGLineCapRound);
        CGContextDrawPath(context, kCGPathStroke);
    }
    if (_isHavePath) {
        CGContextAddPath(context, _path);
        [_lineColor set];
        CGContextSetLineWidth(context, _lineWidth);
        CGContextSetLineCap(context, kCGLineCapRound);
        CGContextDrawPath(context, kCGPathStroke);
    }
}
// 开始touch 的时候
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    UITouch *touch = [touches anyObject];
    CGPoint location = [touch locationInView:self];
    _path = CGPathCreateMutable();
    _isHavePath = YES;
    CGPathMoveToPoint(_path, NULL, location.x, location.y);
}
// 移动的时候
- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    UITouch *touch = [touches anyObject];
    CGPoint location = [touch locationInView:self];
    CGPathAddLineToPoint(_path, NULL, location.x, location.y);
    [self setNeedsDisplay];
}
// 结束时
- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    if (_pathArray == nil) {
        _pathArray = [NSMutableArray array];
    }
    UIBezierPath *path = [UIBezierPath bezierPathWithCGPath:_path];
    ModleOfMyview  *modelOfMyview = [ModleOfMyview viewModelWithColor:_lineColor path:path width:_lineWidth];
    [_pathArray addObject:modelOfMyview];
    CGPathRelease(_path);
    _isHavePath = NO;
}
@end
